<template>
  <div class="addGroup">
    <el-dialog
      :visible="visible"
      :close-on-click-modal="false"
      width="700px"
      :modal-append-to-body="false"
      :show-close="false"
    >
      <div slot="title" class="header">
        <div class="left">
          <div class="icon" />
          <div class="title">上传资料</div>
        </div>
        <div class="close_icon" @click="close" />
      </div>
      <div v-loading="loading">
        <el-form ref="fileForm" label-width="80px" :model="fileForm" :rules="rules">
          <!-- <el-form-item prop="fileType" label="文件类型">
            <el-radio-group v-model="fileForm.fileType">
              <el-radio :label="1">图片</el-radio>
              <el-radio :label="2">音频</el-radio>
              <el-radio :label="3">视频</el-radio>
              <el-radio :label="4">文档</el-radio>
              <el-radio v-for="(item, index) in fileUtils.category" :key="index" :label="index">{{ item }} {{ fileForm.fileType }}</el-radio>
            </el-radio-group>
          </el-form-item> -->
          <el-form-item prop="group_id" label="分组">
            <el-select v-model="fileForm.group_id" placeholder="请选择分组">
              <el-option v-for="(item, index) in groupList" :key="index" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item prop="filename" label="资料名称">
            <el-input
              v-model="fileForm.filename"
              type="text"
              placeholder="请输入内容"
              maxlength="45"
              show-word-limit
            />
          </el-form-item> -->
          <el-form-item prop="file" label="选择文件">
            <el-upload
              ref="fileUpload"
              action=""
              :limit="1"
              :on-change="handleChange"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :auto-upload="false"
              :accept="fileUtils.accept[fileForm.fileType]"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">{{ `只能上传${fileUtils.remark[fileForm.fileType]}文件` }}</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="footer">
        <el-button class="btn" plain @click="close">取消</el-button>
        <el-button class="btn" type="primary" :loading="loading" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Cos from '@/utils/cosUpload'
import SHA256 from 'crypto-js/sha256'
import { extname } from '@/utils'
import { material_add } from '@/api/material'
import { fileUtils } from '@/utils/fileType'
import { media_group_list } from '@/api/material'

export default {
  name: 'FileNameEdit',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    groupId: {
      type: Number,
      default: 1
    },
    fileType: {
      type: Number,
      default: 1
    }
  },
  data() {
    // 这里存放数据
    return {
      fileUtils,
      loading: false,
      rules: {
        fileType: { required: true, message: '请选择文件类型', trigger: 'blur' },
        group_id: { required: true, message: '请选择分组', trigger: 'blur' }
      },
      fileForm: {
        fileType: 4,
        filename: '',
        group_id: '',
        url: '',
        filesize: ''
      },
      file: {},
      cosObj: {},
      groupList: []
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {
    visible(n, o) {
      if (n) {
        this.loadGroupData()
        this.$nextTick(() => {
          this.fileForm.fileType = Number(this.fileType)
          this.fileForm.group_id = Number(this.groupId) || undefined
        })
      }
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  async created() {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() { },
  // 生命周期 - keep-alive
  async activated() {},
  // 方法集合
  methods: {
    submit() {
      const me = this
      me.$refs.fileForm.validate(async(valid) => {
        if (valid) {
          if (!me.file.name) {
            me.$message.warning('请上传文件')
            return
          }
          me.loading = true
          const fileList = await this.handleSha245FileName()
          const file = fileList[0]
          Cos.init.putObject({ // 此处用了最简单的上传函数，此外，腾讯云还支持分片上传函数等等。
            Bucket: Cos.config.Bucket, // 存储桶名称
            Region: Cos.config.Region, // 地区
            Key: `${extname(file.name)}/` + file.name, // 文件名称
            StorageClass: 'STANDARD',
            Body: file.raw, // 上传文件对象
            onHashProgress: function(progressData) {
              console.log('校验中', progressData)
            },
            onProgress: function(progressData) {
              console.log('上传中', progressData)
            }
          },
          async function(err, data) {
            // 这里的data如果是个带有Location等的对象，则说明上传成功。
            if (!err) {
              try {
                const param = new FormData()
                param.append('group_id', me.fileForm.group_id)
                param.append('type', me.fileForm.fileType)
                param.append('url', 'https://' + data.Location)
                param.append('sha1', data.ETag)
                param.append('filename', me.fileForm.filename)
                param.append('mimetype', data.Location.split('.').pop())
                param.append('filesize', me.file.size)
                const { code, message } = await material_add(param)
                if (!code) {
                  me.close()
                  me.$parent.onSearch()
                  me.$message.success(message)
                } else {
                  me.$message.warning(message)
                }
              } catch (error) {
                console.error(error)
              } finally {
                // eslint-disable-next-line require-atomic-updates
                me.loading = false
              }
            } else {
              me.$message.error('上传文件到 Cos 失败')
              me.loading = false
            }
          })
        }
      })
    },
    async loadGroupData() {
      try {
        this.loading = true
        const { code, data } = await media_group_list()
        if (!code) {
          this.groupList = data
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    async handleSha245FileName() {
      const fileList = [1]
      const file = Object.assign({}, this.file)
      const signedFileList = await Promise.all(
        fileList.map((val, index) => {
          return new Promise((resolve, reject) => {
            const fileType = extname(file.name)
            const reader = new FileReader()
            reader.readAsDataURL(file.raw)
            reader.onload = () => {
              const result = reader.result
              const signData = SHA256(result).toString()

              file.name = `${signData}.${fileType}`
              resolve(file)
            }
          })
        }))
      return await signedFileList
    },
    handleChange(file) {
      this.file = file
      if (!this.fileForm.filename) {
        this.fileForm.filename = file.name
      }
    },
    handleRemove(file, fileList) {},
    handlePreview(file) { },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    close() {
      this.file = {}
      this.fileForm = {
        fileType: 4,
        filename: '',
        group_id: '',
        url: '',
        filesize: ''
      }
      this.$refs.fileUpload.clearFiles()
      this.$refs.fileForm.resetFields()
      this.$emit('close')
    }
  },
  // 进入页面前
  beforeRouteEnter(to, from, next) {
    next((vm) => {})
  },
  // 离开页面前
  beforeRouteLeave(to, from, next) {
    next()
  }
}
</script>
<style lang="scss" scoped>
.addGroup {
	.header{
		width: 100%;
		display: flex;
		justify-content: space-between;
    align-items: center;
    background: #FAFAFA;
		.left{
			display: flex;
			.icon{
				background: url('../../assets/dialog/upload.png');
				@include dialog_head_icons;
				height: 14px;
			}
			.title{
				font-size: 14px;
				font-family: SourceHanSansCN-Medium, SourceHanSansCN;
				font-weight: 500;
				color: #000000;
				line-height: 30px;
			}
		}
    .close_icon {
				width:25px;
        height: 24px;
				background: url('../../assets/close-icon.png');
				background-size: 100%;
        cursor: pointer;
		}
	}
  .footer {
    text-align: center;
    .btn{
      width: 80px;
    }
  }
}

::v-deep .el-dialog__body {
    padding: 25px 30px 30px 30px;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
}

::v-deep .el-dialog__footer{
  height: 80px;
  padding: 20px;
  box-shadow: 0px -5px 20px 0px rgba(71, 73, 155, 0.06);
  border-radius: 0px 0px 4px 4px;
}
</style>
